#import "ViewController.h"
#import <Speech/Speech.h>
#import <AVFoundation/AVFoundation.h>
#import "Translations.h"
#import <AudioToolbox/AudioToolbox.h>
#import <MediaPlayer/MediaPlayer.h>

@interface ViewController ()

// 圆形录音按钮
@property (nonatomic, strong) UIButton *recordButton;
// 波纹动画图层
@property (nonatomic, strong) CAShapeLayer *rippleLayer;

// 语音识别
@property (nonatomic, strong) SFSpeechRecognizer *speechRecognizer;
@property (nonatomic, strong) SFSpeechAudioBufferRecognitionRequest *recognitionRequest;
@property (nonatomic, strong) SFSpeechRecognitionTask *recognitionTask;
@property (nonatomic, strong) AVAudioEngine *audioEngine;

// TTS合成
@property (nonatomic, strong) AVSpeechSynthesizer *speechSynthesizer;

// 状态标记
@property (nonatomic, assign) BOOL isRecording;
@property (nonatomic, assign) NSTimeInterval lastAudioTime;
@property (nonatomic, strong) NSString *lastRecognizedText;

// 日志记录
@property (nonatomic, strong) NSMutableArray<NSString *> *logMessages;
@property (nonatomic, assign) NSInteger maxLogCount;

// 重复朗读
@property (nonatomic, strong) NSString *textToRepeat;
@property (nonatomic, assign) NSInteger remainingRepetitions;

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // 初始化日志系统，限制保存最新的10条
    self.maxLogCount = 10;
    self.logMessages = [NSMutableArray arrayWithCapacity:self.maxLogCount];
    
    [self showLog:@"视图加载完成，准备初始化UI..."];
    self.view.backgroundColor = [UIColor colorWithRed:240/255.0 green:248/255.0 blue:255/255.0 alpha:1.0]; // 浅蓝色背景
    [self setupUI];
    [self setupSpeechRecognizer];
    [self setupSpeechSynthesizer];
    self.title = @"快乐英语学习";
    
    // 设置音频会话
    [self setupAudioSession];
    
    // 触发系统声音测试
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [self testSystemSound];
    });
}

- (void)setupUI {
    // 录音按钮 - 大圆形
    self.recordButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [self.recordButton setTitle:@"点我开始说话" forState:UIControlStateNormal];
    self.recordButton.backgroundColor = [UIColor colorWithRed:52/255.0 green:152/255.0 blue:219/255.0 alpha:1.0]; // 蓝色
    self.recordButton.layer.cornerRadius = 100; // 大圆形
    self.recordButton.titleLabel.font = [UIFont systemFontOfSize:24];
    [self.recordButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    
    // 添加阴影效果
    self.recordButton.layer.shadowColor = [UIColor blackColor].CGColor;
    self.recordButton.layer.shadowOffset = CGSizeMake(0, 5);
    self.recordButton.layer.shadowRadius = 10;
    self.recordButton.layer.shadowOpacity = 0.3;
    
    // 确保整个按钮区域可点击
    self.recordButton.contentEdgeInsets = UIEdgeInsetsMake(0, 0, 0, 0);
    self.recordButton.titleEdgeInsets = UIEdgeInsetsMake(0, 0, 0, 0);
    
    [self.recordButton addTarget:self action:@selector(recordButtonTapped) forControlEvents:UIControlEventTouchUpInside];
    
    // 居中放置按钮
    self.recordButton.translatesAutoresizingMaskIntoConstraints = NO;
    [self.view addSubview:self.recordButton];
    
    [NSLayoutConstraint activateConstraints:@[
        [self.recordButton.centerXAnchor constraintEqualToAnchor:self.view.centerXAnchor],
        [self.recordButton.centerYAnchor constraintEqualToAnchor:self.view.centerYAnchor],
        [self.recordButton.widthAnchor constraintEqualToConstant:200],
        [self.recordButton.heightAnchor constraintEqualToConstant:200]
    ]];
    
    // 波纹图层
    self.rippleLayer = [CAShapeLayer layer];
    self.rippleLayer.path = [UIBezierPath bezierPathWithOvalInRect:CGRectMake(0, 0, 200, 200)].CGPath;
    self.rippleLayer.position = CGPointMake(self.view.center.x - 100, self.view.center.y - 100);
    self.rippleLayer.fillColor = [UIColor clearColor].CGColor;
    self.rippleLayer.strokeColor = [UIColor colorWithRed:41/255.0 green:128/255.0 blue:185/255.0 alpha:1.0].CGColor;
    self.rippleLayer.lineWidth = 5;
    self.rippleLayer.opacity = 0;
    [self.view.layer addSublayer:self.rippleLayer];
}

- (void)setupSpeechRecognizer {
    // 设置语音识别，使用中文识别器
    self.speechRecognizer = [[SFSpeechRecognizer alloc] initWithLocale:[NSLocale localeWithLocaleIdentifier:@"zh-CN"]];
    self.speechRecognizer.delegate = self;
    
    self.audioEngine = [[AVAudioEngine alloc] init];
    
    // 请求语音识别权限
    [SFSpeechRecognizer requestAuthorization:^(SFSpeechRecognizerAuthorizationStatus status) {
        BOOL isEnabled = status == SFSpeechRecognizerAuthorizationStatusAuthorized;
        
        dispatch_async(dispatch_get_main_queue(), ^{
            self.recordButton.enabled = isEnabled;
            if (!isEnabled) {
                [self.recordButton setTitle:@"需要语音权限" forState:UIControlStateNormal];
                UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"需要权限" 
                                                                              message:@"请在设置中允许语音识别权限" 
                                                                      preferredStyle:UIAlertControllerStyleAlert];
                [alert addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:nil]];
                [self presentViewController:alert animated:YES completion:nil];
            }
        });
    }];
}

- (void)setupSpeechSynthesizer {
    // 设置语音合成器
    self.speechSynthesizer = [[AVSpeechSynthesizer alloc] init];
    self.speechSynthesizer.delegate = self;
}

- (void)setupAudioSession {
    NSError *error = nil;
    AVAudioSession *audioSession = [AVAudioSession sharedInstance];
    
    // 首先停止任何可能正在运行的音频会话
    [audioSession setActive:NO withOptions:AVAudioSessionSetActiveOptionNotifyOthersOnDeactivation error:nil];
    
    // 强制指定扬声器作为音频输出 - 这是针对iPhone的关键设置
    [audioSession setCategory:AVAudioSessionCategoryPlayAndRecord
                  withOptions:AVAudioSessionCategoryOptionDefaultToSpeaker | 
                              AVAudioSessionCategoryOptionAllowBluetooth |
                              AVAudioSessionCategoryOptionMixWithOthers |
                              AVAudioSessionCategoryOptionDuckOthers  // 添加这个选项以降低其他音频音量
                        error:&error];
    
    if (error) {
        [self showLog:[NSString stringWithFormat:@"设置音频会话类别错误: %@", error]];
        error = nil;  // 重置错误
    }
    
    // 音频会话设置监听通知，以便在音频中断时处理
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(handleAudioSessionInterruption:)
                                                 name:AVAudioSessionInterruptionNotification
                                               object:nil];
    
    // 监听音频路由变化
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(handleAudioRouteChange:)
                                                 name:AVAudioSessionRouteChangeNotification
                                               object:nil];
    
    // 设置应用指向扬声器
    [audioSession overrideOutputAudioPort:AVAudioSessionPortOverrideSpeaker error:&error];
    if (error) {
        [self showLog:[NSString stringWithFormat:@"将音频输出指向扬声器失败: %@", error]];
        error = nil;
    }
    
    // 设置为强制扬声器播放模式
    [audioSession setMode:AVAudioSessionModeSpokenAudio error:&error];
    if (error) {
        [self showLog:[NSString stringWithFormat:@"设置音频会话模式错误: %@", error]];
        error = nil;
    }
    
    // 激活音频会话
    [audioSession setActive:YES withOptions:AVAudioSessionSetActiveOptionNotifyOthersOnDeactivation error:&error];
    if (error) {
        [self showLog:[NSString stringWithFormat:@"激活音频会话错误: %@", error]];
        return;
    }
    
    // 检查当前音量并给出建议
    float currentVolume = audioSession.outputVolume;
    if (currentVolume < 0.5) {
        [self showLog:[NSString stringWithFormat:@"当前系统音量较低: %.2f，建议增大音量", currentVolume]];
    } else {
        [self showLog:[NSString stringWithFormat:@"当前系统音量: %.2f，应该可以听到声音", currentVolume]];
    }
    
    [self showLog:@"音频会话设置成功，使用扬声器作为默认输出"];
    [self checkAudioRoute];
}

- (void)recordButtonTapped {
    if (self.isRecording) {
        [self stopRecording];
    } else {
        [self startRecording];
    }
}

- (void)startRecording {
    // 如果已经有正在运行的识别任务，取消它
    if (self.recognitionTask) {
        [self.recognitionTask cancel];
        self.recognitionTask = nil;
    }
    
    // 确保停止音频引擎以清除之前的状态
    if (self.audioEngine.isRunning) {
        [self.audioEngine stop];
        // 确保移除任何现有的音频tap
        [self.audioEngine.inputNode removeTapOnBus:0];
    }
    
    // 准备音频会话 - 设置为录音模式
    AVAudioSession *audioSession = [AVAudioSession sharedInstance];
    NSError *error;
    [audioSession setCategory:AVAudioSessionCategoryRecord error:&error];
    if (error) {
        [self showLog:[NSString stringWithFormat:@"设置音频会话分类错误: %@", error]];
        return;
    }
    
    [audioSession setActive:YES withOptions:AVAudioSessionSetActiveOptionNotifyOthersOnDeactivation error:&error];
    if (error) {
        [self showLog:[NSString stringWithFormat:@"设置音频会话激活错误: %@", error]];
        return;
    }
    
    // 开始录音
    self.recognitionRequest = [[SFSpeechAudioBufferRecognitionRequest alloc] init];
    
    AVAudioInputNode *inputNode = self.audioEngine.inputNode;
    if (!inputNode) {
        NSLog(@"无法获取音频输入节点");
        return;
    }
    
    self.recognitionRequest.shouldReportPartialResults = YES;
    self.lastRecognizedText = @"";
    
    __weak typeof(self) weakSelf = self;
    self.recognitionTask = [self.speechRecognizer recognitionTaskWithRequest:self.recognitionRequest resultHandler:^(SFSpeechRecognitionResult * _Nullable result, NSError * _Nullable error) {
        __strong typeof(weakSelf) strongSelf = weakSelf;
        
        BOOL isFinal = NO;
        
        if (result) {
            // 更新最后识别的文本
            strongSelf.lastRecognizedText = result.bestTranscription.formattedString;
            
            // 更新最后一次收到音频的时间
            strongSelf.lastAudioTime = [NSDate date].timeIntervalSince1970;
            
            // 检测是否有声音输入
            [strongSelf checkForSilence];
            
            isFinal = result.isFinal;
        }
        
        if (error || isFinal) {
            [strongSelf.audioEngine stop];
            [inputNode removeTapOnBus:0];
            
            strongSelf.recognitionRequest = nil;
            strongSelf.recognitionTask = nil;
        }
    }];
    
    // 设置音频输入
    AVAudioFormat *recordingFormat = [inputNode outputFormatForBus:0];
    [inputNode installTapOnBus:0 bufferSize:1024 format:recordingFormat block:^(AVAudioPCMBuffer * _Nonnull buffer, AVAudioTime * _Nonnull when) {
        [weakSelf.recognitionRequest appendAudioPCMBuffer:buffer];
    }];
    
    [self.audioEngine prepare];
    
    [self.audioEngine startAndReturnError:&error];
    if (error) {
        NSLog(@"音频引擎启动错误: %@", error);
        return;
    }
    
    // 更改UI状态
    self.isRecording = YES;
    [self.recordButton setTitle:@"正在听..." forState:UIControlStateNormal];
    [self.recordButton setBackgroundColor:[UIColor colorWithRed:231/255.0 green:76/255.0 blue:60/255.0 alpha:1.0]]; // 红色
    
    // 启动波纹动画
    [self startRippleAnimation];
    
    // 记录开始录音的时间
    self.lastAudioTime = [NSDate date].timeIntervalSince1970;
    
    // 定时检查是否有声音输入
    [NSTimer scheduledTimerWithTimeInterval:0.5 target:self selector:@selector(checkForSilence) userInfo:nil repeats:YES];
}

- (void)checkForSilence {
    if (!self.isRecording) return;
    
    NSTimeInterval currentTime = [NSDate date].timeIntervalSince1970;
    NSTimeInterval silenceDuration = currentTime - self.lastAudioTime;
    
    // 如果超过2秒没有声音输入，认为用户已经停止说话
    if (silenceDuration > 2.0) {
        [self stopRecording];
    }
}

- (void)stopRecording {
    if (!self.isRecording) return;
    
    [self.audioEngine stop];
    [self.recognitionRequest endAudio];
    
    // 恢复UI状态
    self.isRecording = NO;
    [self.recordButton setTitle:@"点我开始说话" forState:UIControlStateNormal];
    [self.recordButton setBackgroundColor:[UIColor colorWithRed:52/255.0 green:152/255.0 blue:219/255.0 alpha:1.0]]; // 蓝色
    
    // 停止波纹动画
    [self stopRippleAnimation];
    
    // 处理识别的文本
    if (self.lastRecognizedText.length > 0) {
        NSString *chineseText = self.lastRecognizedText;
        [self showLog:[NSString stringWithFormat:@"识别的中文: %@", chineseText]];
        
        // 切换音频会话到播放模式
        [self setupAudioSessionForPlayback];
        
        // 首先检查是否是互动问题
        if ([self isInteractionQuestion:chineseText]) {
            [self respondToInteraction:chineseText];
            return;
        }
        
        // 检查是否是关闭应用的请求
        if ([self isCloseAppRequest:chineseText]) {
            [self respondToCloseAppRequest];
            return;
        }
        
        // 使用外部词汇表
        NSDictionary *translations = GetTranslationsDictionary();
        
        // 改进匹配逻辑
        NSString *englishText = nil;
        
        // 精确匹配
        englishText = translations[chineseText];
        
        // 如果精确匹配失败，尝试检查完整句子中是否包含词汇表中的词
        if (!englishText) {
            for (NSString *key in translations) {
                if ([chineseText containsString:key]) {
                    // 找到匹配的词，用这个词的翻译替换
                    englishText = [NSString stringWithFormat:@"%@ (%@)", translations[key], key];
                    break;
                }
            }
        }
        
        // 如果仍然没有匹配成功，使用默认回复
        if (!englishText) {
            englishText = @"Sorry, I don't know how to translate that yet.";
        }
        
        // 创建富文本消息，英文部分加粗并显示为蓝色
        NSMutableAttributedString *message = [self createAttributedResultWithChinese:chineseText english:englishText];
        
        // 创建并显示带有富文本的弹窗
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"识别结果" 
                                                                       message:nil
                                                                preferredStyle:UIAlertControllerStyleAlert];
        
        // 设置富文本值属性
        [alert setValue:message forKey:@"attributedMessage"];
        
        // 添加确定按钮 - 由于无法直接设置按钮字体，我们创建自定义按钮样式
        UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault 
                                                         handler:^(UIAlertAction * _Nonnull action) {
            // 用户点击确定时停止朗读
            [self stopSpeaking];
        }];
        
        [alert addAction:okAction];
        
        // 通过运行时修改按钮外观 - 警告：这是一种hack方式
        // 显示弹窗
        [self presentViewController:alert animated:YES completion:^{
            // 在弹窗显示完成后尝试访问其中的按钮
            UIView *alertView = alert.view;
            
            // 在弹窗视图层次结构中查找按钮
            NSArray *subviews = alertView.subviews;
            for (UIView *subview in subviews) {
                NSArray *actionViews = subview.subviews;
                for (UIView *actionView in actionViews) {
                    // 查找包含确定按钮的容器
                    if ([actionView isKindOfClass:[UIStackView class]]) {
                        UIStackView *stackView = (UIStackView *)actionView;
                        for (UIView *buttonContainer in stackView.arrangedSubviews) {
                            // 遍历容器中的视图寻找按钮
                            for (UIView *possibleButton in buttonContainer.subviews) {
                                if ([possibleButton isKindOfClass:[UIButton class]]) {
                                    UIButton *button = (UIButton *)possibleButton;
                                    // 修改按钮标题的字体
                                    [button.titleLabel setFont:[UIFont boldSystemFontOfSize:25.0]];
                                }
                            }
                        }
                    }
                }
            }
        }];
        
        // 使用TTS朗读英文3遍
        [self speakTextThreeTimes:englishText];
        
        // 添加观察者监听弹窗消失
        [[NSNotificationCenter defaultCenter] addObserver:self
                                                 selector:@selector(stopSpeaking)
                                                     name:UIWindowDidBecomeHiddenNotification
                                                   object:nil];
    }
}

// 创建带格式的结果文本，英文加粗并显示为蓝色
- (NSMutableAttributedString *)createAttributedResultWithChinese:(NSString *)chineseText english:(NSString *)englishText {
    // 创建富文本字符串
    NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] init];
    
    // 设置基本字体大小，比默认大8号
    UIFont *baseFont = [UIFont systemFontOfSize:20.0]; // 默认通常是12-14
    UIFont *boldFont = [UIFont boldSystemFontOfSize:30.0]; // 英文字体增大到30号
    UIColor *blueColor = [UIColor colorWithRed:0.0/255.0 green:122.0/255.0 blue:255.0/255.0 alpha:1.0];
    
    // 添加中文部分
    NSAttributedString *chineseAttributed = [[NSAttributedString alloc] 
                                             initWithString:[NSString stringWithFormat:@"中文: %@\n", chineseText]
                                             attributes:@{NSFontAttributeName: baseFont}];
    [attributedString appendAttributedString:chineseAttributed];
    
    // 添加"英文: "部分
    NSAttributedString *englishLabel = [[NSAttributedString alloc] 
                                        initWithString:@"英文: "
                                        attributes:@{NSFontAttributeName: baseFont}];
    [attributedString appendAttributedString:englishLabel];
    
    // 提取英文部分和中文注释部分
    NSString *englishPart = englishText;
    NSString *chineseNote = @"";
    
    // 如果英文包含括号，将括号中的内容作为中文注释
    NSRange bracketRange = [englishText rangeOfString:@" ("];
    if (bracketRange.location != NSNotFound) {
        englishPart = [englishText substringToIndex:bracketRange.location];
        
        // 查找右括号
        NSRange closeBracketRange = [englishText rangeOfString:@")" options:0 range:NSMakeRange(bracketRange.location, englishText.length - bracketRange.location)];
        if (closeBracketRange.location != NSNotFound) {
            chineseNote = [englishText substringWithRange:NSMakeRange(bracketRange.location + 2, closeBracketRange.location - bracketRange.location - 2)];
        }
    }
    
    // 添加英文翻译部分（加粗、蓝色，字体更大）
    NSAttributedString *englishAttributed = [[NSAttributedString alloc] 
                                             initWithString:englishPart
                                             attributes:@{
                                                 NSFontAttributeName: boldFont,
                                                 NSForegroundColorAttributeName: blueColor
                                             }];
    [attributedString appendAttributedString:englishAttributed];
    
    // 如果有中文注释，另起一行并居中显示
    if (chineseNote.length > 0) {
        // 添加换行
        NSAttributedString *newLine = [[NSAttributedString alloc] initWithString:@"\n" attributes:@{NSFontAttributeName: baseFont}];
        [attributedString appendAttributedString:newLine];
        
        // 创建段落样式使注释居中
        NSMutableParagraphStyle *centerStyle = [[NSMutableParagraphStyle alloc] init];
        centerStyle.alignment = NSTextAlignmentCenter;
        
        // 添加居中的中文注释
        NSAttributedString *noteAttributed = [[NSAttributedString alloc] 
                                              initWithString:[NSString stringWithFormat:@"(%@)", chineseNote]
                                              attributes:@{
                                                  NSFontAttributeName: baseFont,
                                                  NSParagraphStyleAttributeName: centerStyle
                                              }];
        [attributedString appendAttributedString:noteAttributed];
    }
    
    return attributedString;
}

// 朗读文本3遍
- (void)speakTextThreeTimes:(NSString *)text {
    if (!text || text.length == 0) {
        [self showLog:@"错误: 要朗读的文本为空"];
        return;
    }
    
    [self showLog:[NSString stringWithFormat:@"准备朗读文本3遍: %@", text]];
    
    // 存储要朗读的文本以便重复
    self.textToRepeat = text;
    self.remainingRepetitions = 3;
    
    // 开始第一次朗读
    [self speakText:text];
}

// 停止朗读
- (void)stopSpeaking {
    if ([self.speechSynthesizer isSpeaking]) {
        [self.speechSynthesizer stopSpeakingAtBoundary:AVSpeechBoundaryImmediate];
        [self showLog:@"已停止朗读"];
    }
    
    // 重置重复计数
    self.remainingRepetitions = 0;
    self.textToRepeat = nil;
    
    // 重要: 在停止后重新初始化语音合成器
    self.speechSynthesizer = nil;
    
    // 延迟重新初始化合成器和音频会话
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.3 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        // 重新初始化语音合成器
        self.speechSynthesizer = [[AVSpeechSynthesizer alloc] init];
        self.speechSynthesizer.delegate = self;
        
        // 重置音频会话
        [self setupAudioSessionForPlayback];
        
        [self showLog:@"语音合成器已重置，准备下一次朗读"];
    });
    
    // 移除通知观察
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIWindowDidBecomeHiddenNotification object:nil];
}

// 检查是否是互动问题
- (BOOL)isInteractionQuestion:(NSString *)text {
    NSArray *interactionKeywords = @[
        @"你是谁", @"你叫什么", @"你叫什么名字", @"你的名字", @"你好", 
        @"你几岁", @"你多大了", @"你住在哪里", @"你能做什么"
    ];
    
    for (NSString *keyword in interactionKeywords) {
        if ([text containsString:keyword]) {
            return YES;
        }
    }
    
    return NO;
}

// 回应互动问题
- (void)respondToInteraction:(NSString *)question {
    NSString *response = @"我是你的好朋友乐乐，可以教你学英语哦！";
    
    if ([question containsString:@"几岁"] || [question containsString:@"多大"]) {
        response = @"我今年6岁啦，我很喜欢和你一起学习英语！";
    } else if ([question containsString:@"住在哪"]) {
        response = @"我住在你的手机里，随时可以陪你学习英语！";
    } else if ([question containsString:@"能做什么"]) {
        response = @"我可以帮你把中文翻译成英文，和你一起快乐学英语！";
    } else if ([question containsString:@"你好"]) {
        response = @"你好呀！我是乐乐，很高兴认识你！";
    }
    
    // 显示回应
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"乐乐回应" 
                                                                  message:response
                                                           preferredStyle:UIAlertControllerStyleAlert];
    [alert addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:nil]];
    [self presentViewController:alert animated:YES completion:nil];
    
    // 使用中文女声童声回应
    [self speakChineseText:response];
}

// 使用中文女声朗读文本
- (void)speakChineseText:(NSString *)text {
    if (!text || text.length == 0) {
        return;
    }
    
    // 强制设置为播放模式
    [self setupAudioSessionForPlayback];
    
    // 创建语音合成请求
    AVSpeechUtterance *utterance = [AVSpeechUtterance speechUtteranceWithString:text];
    
    // 寻找中文女声，优先使用童声
    AVSpeechSynthesisVoice *selectedVoice = nil;
    NSArray *voices = [AVSpeechSynthesisVoice speechVoices];
    
    // 首先尝试找到中文女童声
    for (AVSpeechSynthesisVoice *voice in voices) {
        if ([voice.language hasPrefix:@"zh"] && 
            ([voice.identifier containsString:@"female"] || [voice.identifier containsString:@"girl"])) {
            selectedVoice = voice;
            [self showLog:[NSString stringWithFormat:@"找到中文女声: %@", voice.identifier]];
            break;
        }
    }
    
    // 如果没找到特定的童声，使用任何中文女声
    if (!selectedVoice) {
        for (AVSpeechSynthesisVoice *voice in voices) {
            if ([voice.language hasPrefix:@"zh"]) {
                selectedVoice = voice;
                [self showLog:[NSString stringWithFormat:@"找到中文声音: %@", voice.identifier]];
                break;
            }
        }
    }
    
    // 如果仍未找到，使用默认中文声音
    if (selectedVoice) {
        utterance.voice = selectedVoice;
    } else {
        utterance.voice = [AVSpeechSynthesisVoice voiceWithLanguage:@"zh-CN"];
        [self showLog:@"使用默认中文声音"];
    }
    
    // 提高音量，调整发音速率和音调使其听起来更像童声
    utterance.rate = 0.5;        // 较慢的语速，适合孩子听
    utterance.pitchMultiplier = 1.5; // 提高音调，使其听起来更像童声
    utterance.volume = 1.0;      // 最大音量
    
    [self showLog:@"开始朗读中文..."];
    
    // 停止任何正在进行的朗读
    if ([self.speechSynthesizer isSpeaking]) {
        [self.speechSynthesizer stopSpeakingAtBoundary:AVSpeechBoundaryImmediate];
    }
    
    // 直接开始语音合成
    [self.speechSynthesizer speakUtterance:utterance];
}

- (void)speakText:(NSString *)text {
    if (!text || text.length == 0) {
        [self showLog:@"错误: 要朗读的文本为空"];
        return;
    }
    
    [self showLog:[NSString stringWithFormat:@"准备朗读文本: %@", text]];
    
    // 强制设置为播放模式
    [self setupAudioSessionForPlayback];
    
    // 确保语音合成器已初始化
    if (!self.speechSynthesizer) {
        [self showLog:@"重新初始化语音合成器"];
        self.speechSynthesizer = [[AVSpeechSynthesizer alloc] init];
        self.speechSynthesizer.delegate = self;
    }
    
    // 使用英语声音
    AVSpeechUtterance *utterance = [AVSpeechUtterance speechUtteranceWithString:text];
    
    // 检查是否有可用的英语声音
    NSArray *voices = [AVSpeechSynthesisVoice speechVoices];
    AVSpeechSynthesisVoice *selectedVoice = nil;
    
    [self showLog:[NSString stringWithFormat:@"可用语音数量: %lu", (unsigned long)voices.count]];
    
    // 优先寻找英语女童声
    for (AVSpeechSynthesisVoice *voice in voices) {
        if ([voice.language hasPrefix:@"en"] && 
            ([voice.identifier containsString:@"female"] || [voice.identifier containsString:@"girl"])) {
            selectedVoice = voice;
            [self showLog:[NSString stringWithFormat:@"找到英语女声: %@", voice.identifier]];
            break;
        }
    }
    
    // 如果没找到女童声，尝试找任何英语声音
    if (!selectedVoice) {
        for (AVSpeechSynthesisVoice *voice in voices) {
            [self showLog:[NSString stringWithFormat:@"- %@: %@", voice.identifier, voice.language]];
            if ([voice.language hasPrefix:@"en"]) {
                selectedVoice = voice;
                [self showLog:[NSString stringWithFormat:@"找到英语声音: %@", voice.identifier]];
                break;
            }
        }
    }
    
    if (selectedVoice) {
        utterance.voice = selectedVoice;
    } else {
        utterance.voice = [AVSpeechSynthesisVoice voiceWithLanguage:@"en-US"];
        [self showLog:@"使用默认英语声音"];
    }
    
    // 增大音量和调整音调，使其听起来更像童声
    utterance.rate = 0.4;         // 较慢的语速，适合儿童学习
    utterance.pitchMultiplier = 1.3; // 提高音调，使其听起来更像童声
    utterance.volume = 1.0;       // 最大音量
    utterance.preUtteranceDelay = 0.5; // 增加延迟，确保系统准备好播放
    
    [self showLog:@"开始朗读..."];
    
    // 停止任何正在进行的朗读
    if ([self.speechSynthesizer isSpeaking]) {
        [self.speechSynthesizer stopSpeakingAtBoundary:AVSpeechBoundaryImmediate];
    }
    
    // 使用try-catch捕获可能的异常
    @try {
        [self.speechSynthesizer speakUtterance:utterance];
    } @catch (NSException *exception) {
        [self showLog:[NSString stringWithFormat:@"朗读时发生异常: %@", exception]];
        
        // 重新初始化语音合成器并尝试再次朗读
        self.speechSynthesizer = [[AVSpeechSynthesizer alloc] init];
        self.speechSynthesizer.delegate = self;
        
        // 重新设置音频会话
        [self setupAudioSessionForPlayback];
        
        // 延迟后再尝试一次
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [self.speechSynthesizer speakUtterance:utterance];
        });
    }
}

#pragma mark - 动画方法

- (void)startRippleAnimation {
    self.rippleLayer.opacity = 1.0;
    
    CABasicAnimation *pulseAnimation = [CABasicAnimation animationWithKeyPath:@"transform.scale"];
    pulseAnimation.duration = 1.0;
    pulseAnimation.fromValue = @1.0;
    pulseAnimation.toValue = @1.2;
    pulseAnimation.autoreverses = YES;
    pulseAnimation.repeatCount = HUGE_VALF;
    pulseAnimation.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];
    
    CABasicAnimation *opacityAnimation = [CABasicAnimation animationWithKeyPath:@"opacity"];
    opacityAnimation.duration = 1.0;
    opacityAnimation.fromValue = @1.0;
    opacityAnimation.toValue = @0.5;
    opacityAnimation.autoreverses = YES;
    opacityAnimation.repeatCount = HUGE_VALF;
    opacityAnimation.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];
    
    [self.rippleLayer addAnimation:pulseAnimation forKey:@"pulse"];
    [self.rippleLayer addAnimation:opacityAnimation forKey:@"opacity"];
}

- (void)stopRippleAnimation {
    [self.rippleLayer removeAllAnimations];
    self.rippleLayer.opacity = 0;
}

#pragma mark - AVSpeechSynthesizerDelegate

// 添加代理方法来帮助调试语音合成
- (void)speechSynthesizer:(AVSpeechSynthesizer *)synthesizer didStartSpeechUtterance:(AVSpeechUtterance *)utterance {
    [self showLog:[NSString stringWithFormat:@"语音合成开始: %@", utterance.speechString]];
}

- (void)speechSynthesizer:(AVSpeechSynthesizer *)synthesizer didFinishSpeechUtterance:(AVSpeechUtterance *)utterance {
    [self showLog:[NSString stringWithFormat:@"语音合成结束: %@", utterance.speechString]];
    
    // 如果需要重复朗读，继续下一次朗读
    if (self.remainingRepetitions > 1 && self.textToRepeat) {
        self.remainingRepetitions--;
        [self showLog:[NSString stringWithFormat:@"还剩 %ld 次朗读", (long)self.remainingRepetitions]];
        
        // 在进行下一次朗读前确保音频会话处于正确状态
        [self setupAudioSessionForPlayback];
        
        // 延迟一小段时间再开始下一次朗读
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.8 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [self speakText:self.textToRepeat];
        });
    } else {
        // 朗读完成后重置
        self.remainingRepetitions = 0;
        self.textToRepeat = nil;
    }
}

- (void)speechSynthesizer:(AVSpeechSynthesizer *)synthesizer didPauseSpeechUtterance:(AVSpeechUtterance *)utterance {
    [self showLog:@"语音合成暂停"];
}

- (void)speechSynthesizer:(AVSpeechSynthesizer *)synthesizer didContinueSpeechUtterance:(AVSpeechUtterance *)utterance {
    [self showLog:@"语音合成继续"];
}

- (void)speechSynthesizer:(AVSpeechSynthesizer *)synthesizer didCancelSpeechUtterance:(AVSpeechUtterance *)utterance {
    [self showLog:@"语音合成取消"];
}

- (void)speechSynthesizer:(AVSpeechSynthesizer *)synthesizer willSpeakRangeOfSpeechString:(NSRange)characterRange utterance:(AVSpeechUtterance *)utterance {
    NSLog(@"正在朗读文本部分: %@", [utterance.speechString substringWithRange:characterRange]);
}

// 添加查看日志的按钮
- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    
    // 添加查看日志按钮
    UIButton *logButton = [UIButton buttonWithType:UIButtonTypeSystem];
    [logButton setTitle:@"查看日志" forState:UIControlStateNormal];
    logButton.backgroundColor = [UIColor colorWithWhite:0.9 alpha:1.0];
    logButton.layer.cornerRadius = 10;
    [logButton addTarget:self action:@selector(showFullLog) forControlEvents:UIControlEventTouchUpInside];
    
    logButton.translatesAutoresizingMaskIntoConstraints = NO;
    [self.view addSubview:logButton];
    
    [NSLayoutConstraint activateConstraints:@[
        [logButton.topAnchor constraintEqualToAnchor:self.view.safeAreaLayoutGuide.topAnchor constant:20],
        [logButton.trailingAnchor constraintEqualToAnchor:self.view.trailingAnchor constant:-20],
        [logButton.widthAnchor constraintEqualToConstant:100],
        [logButton.heightAnchor constraintEqualToConstant:40]
    ]];
}

// 检查是否要关闭应用程序
- (BOOL)isCloseAppRequest:(NSString *)text {
    // 检查文本中是否包含关闭或停止的关键词
    NSArray *closeKeywords = @[@"关闭", @"停止", @"退出", @"结束", @"停下", @"不玩了"];
    
    for (NSString *keyword in closeKeywords) {
        if ([text containsString:keyword]) {
            return YES;
        }
    }
    
    return NO;
}

// 响应关闭应用的请求
- (void)respondToCloseAppRequest {
    [self stopRecording];
    [self stopSpeaking];
    
    // 播放提示音
    AudioServicesPlaySystemSound(1521); // 播放一个系统提示音
    
    // 告知用户可以退出应用
    [self speakChineseText:@"好的，现在您可以关闭应用了，下次再见！"];
    
    // 显示一个对话框提示用户
    dispatch_async(dispatch_get_main_queue(), ^{
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" 
                                                                      message:@"应用已停止服务，您可以点击Home键退出应用。"
                                                               preferredStyle:UIAlertControllerStyleAlert];
        [alert addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:nil]];
        [self presentViewController:alert animated:YES completion:nil];
    });
    
    [self showLog:@"用户请求关闭应用，已停止所有服务"];
}

// 辅助方法：显示日志并弹窗
- (void)showLog:(NSString *)message {
    NSLog(@"%@", message);
    
    // 添加到日志记录，保持最新的10条
    [self addLogMessage:message];
    
    // 为避免过多弹窗干扰用户，只在关键信息时弹窗
    if ([message containsString:@"错误"] || 
        [message containsString:@"识别的中文"] || 
        [message containsString:@"开始朗读"] ||
        [message containsString:@"语音合成开始"]) {
        
        dispatch_async(dispatch_get_main_queue(), ^{
            UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"日志信息" 
                                                                          message:message
                                                                   preferredStyle:UIAlertControllerStyleAlert];
            [alert addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:nil]];
            [self presentViewController:alert animated:YES completion:nil];
        });
    }
}

// 添加日志消息，保持最多maxLogCount条
- (void)addLogMessage:(NSString *)message {
    if (self.logMessages.count >= self.maxLogCount) {
        // 移除最旧的日志
        [self.logMessages removeObjectAtIndex:0];
    }
    // 添加新日志
    [self.logMessages addObject:message];
}

// 显示完整日志的方法
- (void)showFullLog {
    // 将数组中的日志消息合并为一个字符串
    NSString *logText = [self.logMessages componentsJoinedByString:@"\n"];
    
    dispatch_async(dispatch_get_main_queue(), ^{
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"最新日志" 
                                                                      message:logText
                                                               preferredStyle:UIAlertControllerStyleAlert];
        [alert addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:nil]];
        [self presentViewController:alert animated:YES completion:nil];
    });
}

// 测试系统声音
- (void)testSystemSound {
    [self showLog:@"测试系统声音..."];
    
    // 强制设置为播放模式
    [self setupAudioSessionForPlayback];
    
    // 播放不同的系统声音以测试音频输出
    AudioServicesPlaySystemSound(kSystemSoundID_Vibrate); // 震动
    
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        AudioServicesPlaySystemSound(1000); // UI 按键音效
        
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            AudioServicesPlaySystemSound(1307); // 另一个系统声音
            
            // 检查音频路由
            [self checkAudioRoute];
        });
    });
}

// 检查当前音频路由
- (void)checkAudioRoute {
    AVAudioSession *session = [AVAudioSession sharedInstance];
    AVAudioSessionRouteDescription *route = session.currentRoute;
    
    NSMutableString *routeInfo = [NSMutableString stringWithString:@"当前音频路由:\n"];
    
    for (AVAudioSessionPortDescription *output in route.outputs) {
        [routeInfo appendFormat:@"输出: %@ (类型: %@)\n", output.portName, output.portType];
    }
    
    for (AVAudioSessionPortDescription *input in route.inputs) {
        [routeInfo appendFormat:@"输入: %@ (类型: %@)\n", input.portName, input.portType];
    }
    
    [self showLog:routeInfo];
}

// 处理音频会话中断
- (void)handleAudioSessionInterruption:(NSNotification *)notification {
    NSInteger type = [notification.userInfo[AVAudioSessionInterruptionTypeKey] integerValue];
    
    if (type == AVAudioSessionInterruptionTypeBegan) {
        [self showLog:@"音频会话被中断"];
        
        // 如果正在说话，则停止
        if ([self.speechSynthesizer isSpeaking]) {
            [self.speechSynthesizer stopSpeakingAtBoundary:AVSpeechBoundaryImmediate];
        }
    } 
    else if (type == AVAudioSessionInterruptionTypeEnded) {
        NSInteger option = [notification.userInfo[AVAudioSessionInterruptionOptionKey] integerValue];
        
        if (option == AVAudioSessionInterruptionOptionShouldResume) {
            [self showLog:@"音频会话中断结束，重新设置"];
            
            // 重新设置音频会话
            [self setupAudioSessionForPlayback];
        }
    }
}

// 处理音频路由变化
- (void)handleAudioRouteChange:(NSNotification *)notification {
    NSInteger reason = [notification.userInfo[AVAudioSessionRouteChangeReasonKey] integerValue];
    
    [self showLog:[NSString stringWithFormat:@"音频路由变化，原因: %ld", (long)reason]];
    
    // 在路由变化后，检查并确保使用扬声器
    if (reason != AVAudioSessionRouteChangeReasonCategoryChange) { // 忽略类别变化引起的路由变化
        NSError *error = nil;
        [[AVAudioSession sharedInstance] overrideOutputAudioPort:AVAudioSessionPortOverrideSpeaker error:&error];
        
        if (error) {
            [self showLog:[NSString stringWithFormat:@"路由变化后设置扬声器失败: %@", error]];
        } else {
            [self showLog:@"路由变化后已重新设置为使用扬声器"];
        }
    }
    
    // 更新音频路由信息
    [self checkAudioRoute];
}

- (void)setupAudioSessionForPlayback {
    NSError *error = nil;
    AVAudioSession *audioSession = [AVAudioSession sharedInstance];
    
    // 先停用现有会话
    [audioSession setActive:NO withOptions:AVAudioSessionSetActiveOptionNotifyOthersOnDeactivation error:nil];
    
    // 设置为播放模式，并明确指定使用扬声器
    [audioSession setCategory:AVAudioSessionCategoryPlayback
                  withOptions:AVAudioSessionCategoryOptionDuckOthers
                        error:&error];
    if (error) {
        [self showLog:[NSString stringWithFormat:@"设置播放模式错误: %@", error]];
        error = nil;
    }
    
    // 强制使用扬声器输出
    [audioSession overrideOutputAudioPort:AVAudioSessionPortOverrideSpeaker error:&error];
    if (error) {
        [self showLog:[NSString stringWithFormat:@"强制使用扬声器失败: %@", error]];
        error = nil;
    }
    
    // 设置为语音播放模式
    [audioSession setMode:AVAudioSessionModeSpokenAudio error:&error];
    if (error) {
        [self showLog:[NSString stringWithFormat:@"设置会话模式失败: %@", error]];
        error = nil;
    }
    
    // 激活会话
    [audioSession setActive:YES withOptions:AVAudioSessionSetActiveOptionNotifyOthersOnDeactivation error:&error];
    if (error) {
        [self showLog:[NSString stringWithFormat:@"激活播放会话错误: %@", error]];
        return;
    }
    
    // 检查当前音量并给出建议
    float currentVolume = audioSession.outputVolume;
    if (currentVolume < 0.5) {
        [self showLog:[NSString stringWithFormat:@"当前系统音量较低: %.2f，建议增大音量", currentVolume]];
    } else {
        [self showLog:[NSString stringWithFormat:@"当前系统音量: %.2f，应该可以听到声音", currentVolume]];
    }
    
    [self showLog:@"已切换到播放模式并强制使用扬声器"];
    [self checkAudioRoute];
}

@end 